// 导入three.js
import * as THREE from "three";
// 导入轨道控制器
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
// 导入GUI
import { GUI } from "three/examples/jsm/libs/lil-gui.module.min.js"
// 导入hdr加载器
import { RGBELoader } from "three/examples/jsm/loaders/RGBELoader.js"
// 导入gltf加载器
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js"
// 导入draco解码器
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader.js"

// 创建场景
const scene = new THREE.Scene()
// scene.background = new THREE.Color("#c6c6c6")
// 创建相机
const camera = new THREE.PerspectiveCamera(
  45, // 视角
  window.innerWidth / window.innerHeight, //宽高比
  0.1, // 近平面
  1000 // 远平面
)

// 创建渲染器
const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight) // 设置渲染器宽高
document.body.appendChild(renderer.domElement) // 将渲染器添加到body中

// 创建轨道控制器
const controls = new OrbitControls(camera, renderer.domElement)
controls.enableDamping = true // 开启阻尼
controls.dampingFactor = 0.05 // 阻尼系数

// 设置相机位置
camera.position.z = 15
camera.position.y = 4
camera.position.x = 2
camera.lookAt(0, 0, 0)

// 添加世界辅助坐标器
const axisHelper = new THREE.AxesHelper(5)
scene.add(axisHelper)

function init() {
  controls.update() // 更新控制器
  requestAnimationFrame(init);
  renderer.render(scene, camera) // 渲染场景和相机
}

init() //初始化
// 创建GUI
const gui = new GUI()

// 创建三个球
const sphere1 = new THREE.Mesh(
  new THREE.SphereGeometry(1, 32, 32),
  new THREE.MeshBasicMaterial({ color: "#00affa" })
)
sphere1.position.x = -4
scene.add(sphere1)

const sphere2 = new THREE.Mesh(
  new THREE.SphereGeometry(1, 32, 32),
  new THREE.MeshBasicMaterial({ color: "#0fffa0" })
)
scene.add(sphere2)

const sphere3 = new THREE.Mesh(
  new THREE.SphereGeometry(1, 32, 32),
  new THREE.MeshBasicMaterial({ color: "#00ffff" })
)
sphere3.position.x = 4
scene.add(sphere3)

console.log(scene.children)

// 创建射线
const raycaster = new THREE.Raycaster()
// 创建鼠标
const mouse = new THREE.Vector2()

window.addEventListener("click",(e)=>{
  // 将鼠标坐标转换成threejs坐标
  mouse.x = (e.clientX / window.innerWidth) * 2 - 1
  mouse.y = -(e.clientY / window.innerHeight) * 2 + 1

  // 通过相机和鼠标位置更新射线
  raycaster.setFromCamera(mouse, camera)

  // 计算射线和场景的交点
  const intersects = raycaster.intersectObjects([sphere1,sphere2,sphere3])
  intersects.forEach((item,index)=>{
    if(!item) return
    if(index !== 0) return

    if(item.object._selected){
      item.object._selected = false
      item.object.material.color.setHex(item.object._originColor)
      return
    }

    item.object._selected = true
    item.object._originColor = item.object.material.color.getHex()
    item.object.material.color.set("#ff0000")
  })
})